//  
//  Copyright © 2009 Jiří Zárevúcky <zarevucky.jiri@gmail.com>
// 
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
// 
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
// 
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
// 

using System;
using System.Collections.Generic;

using Gdk;
using Gtk;

using L=Galaxium.Protocol.Xmpp.Library;
using Galaxium.Protocol.Xmpp.Library;

namespace Galaxium.Protocol.Xmpp.GtkGui
{
	public class ContactSelectionWidget: TreeView
	{
	//	private bool _allow_multiple;
		private bool _display_avatars;
		
		public List<JabberID> Selected { get; private set; }

	//	public event EventHandler SelectionChanged;
		
		public ContactSelectionWidget (L.Client client, bool allow_multiple, bool display_avatars)
		{
		//	_allow_multiple = allow_multiple;
			_display_avatars = display_avatars;
			
			Model = new ListStore (typeof (Boolean), typeof (JabberID),
			                       typeof (String), typeof (Gdk.Pixbuf));

			if (allow_multiple) {
				AppendColumn (String.Empty, new CellRendererToggle (), "active", 0);
			}
			var col = new TreeViewColumn ();
			CellRenderer cell = new CellRendererText ();
			col.PackStart (cell, true);
			col.SetAttributes (cell, "text", 2);
			if (display_avatars) {
				cell = new CellRendererPixbuf ();
				col.PackStart (cell, false);
				col.SetAttributes (cell, "pixbuf", 3);
			}
			AppendColumn (col);
			
			Populate (client);
			InitSort ();

			this.ButtonPressEvent += delegate (object o, ButtonPressEventArgs args) {
				if (!allow_multiple) return;
				TreePath path;
				if (this.GetPathAtPos ((int) args.Event.X, (int) args.Event.Y, out path)) {
					TreeIter iter;
					if (this.Model.GetIter (out iter, path))
						this.Model.SetValue (iter, 0, !(bool)this.Model.GetValue (iter, 0));
				}
			}; // TODO: allow keyboard handling
		}

		private void Populate (L.Client client)
		{
			foreach (Contact contact in client.Roster)
				AddEntry (contact.Jid, contact.Name, null, false);
		}

		private void InitSort ()
		{
			(Model as TreeSortable).DefaultSortFunc = (model, iter1, iter2) => {
				return (model.GetValue (iter1, 2) as string)
				.CompareTo (model.GetValue (iter2, 2) as string);
			};
		}

		public void AddEntry (JabberID jid, string name, Pixbuf image, bool selected)
		{
			(Model as ListStore).AppendValues (selected, jid, name,
			                                   _display_avatars ? image : null);
		}
	}
}
